package com.byq.mm.smartlib.obd.commands.decoder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;


public class DecoderManager {
	
	
	Map<String, CommandDecoder> decoders = SupportedDecoders.getSupportedDecoders();
	public Map<String,CommandDecoder> getGroupedDecoders(String group){
		Map<String,CommandDecoder> rst = new HashMap<String,CommandDecoder>();
		for(CommandDecoder cd : decoders.values()){
			if(cd.getGroup().equals(group))
				rst.put(cd.getKey(), cd);
		}
		return rst;
	}
	public Map<String, CommandDecoder> decoders(){
		return decoders;
	}
	public List<Map<String,CommandDecoder>> split(Map<String,CommandDecoder> ds){
		
		List<Map<String,CommandDecoder>> rst = new ArrayList<Map<String,CommandDecoder>>();
		Map<String,CommandDecoder> ii = null;
		int i = 0;
		for(CommandDecoder cd : ds.values()){
			if(i % 4 == 0){
				ii = new HashMap<String,CommandDecoder>();
				rst.add(ii);
			}
			ii.put(cd.getKey(), cd);
			i++;
		}
		return rst;
	}
	
	public CommandDecoder getDecoderByKey(String key) {
		// TODO Auto-generated method stub
		return decoders.get(key);
	}
	public Set<String> groups(){
		Set<String> rst = new HashSet<String>();
		for(CommandDecoder cd : decoders.values())
			rst.add(cd.getGroup());
		return rst;
		
	}
	public void simulate(){
		for(CommandDecoder cd : decoders.values())
			cd.simulate();
		
		
	}
	public  byte[] encode(){
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		for (CommandDecoder cd : decoders.values()) {
			try {
				out.write(cd.response);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return out.toByteArray();
	}
	public void decode(byte[] data) {
		if(data == null || data.length == 0)
			return;
		int startIndex = 0;
		while(true){
			CommandDecoder decoder = getDecoder(data, startIndex);
			int i = decoder.eat(data, startIndex);
			startIndex += i;
		}

	}

	private CommandDecoder getDecoder(byte[] data, int startIndex) {
		return getDecoderByKey("" + data[startIndex] + data[startIndex + 1]);
	}

/*	static public void main(String[] ss){
		FuelConsumption cd = new FuelConsumption();
		for(int i = 0; i < 100; i++){
			cd.simulate();
			double v = cd.getValue();
			System.out.println(v);
		}
	}*/
}
